import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { useState } from 'react'
import {
  AtInputNumber,
  AtModal,
  // AtModalHeader,
  // AtModalContent,
  // AtModalAction,
  AtMessage,
} from 'taro-ui'
import { getGoodById } from '@/api/home'
import { addOrder, getGoodDetail } from '@/api/myOrder'

import styles from './index.module.scss'

type ProductDetail = {
  id: number
  name: string
  coverUrl: string
  price: number
  isOver: boolean
  isCollect: boolean
  description: string
  imgs: any[] // 由于imgs是空的，我们可以暂时定义它为any[]，或者根据需要更精确地定义
  weight: number
  unit: string
  note: string
  content: string
}
export default function Pay() {
  const router = useRouter()
  const [money, setMoney] = useState(70.99)
  const [goodsNumber, setGoodsNumber] = useState(1)
  const [totalMoney, setTotalMoney] = useState(70.99)
  const [showModal, setShowModal] = useState(false)
  const [productDetail, setProductDetail] = useState<ProductDetail>({})
  const [showNewOrderModal, setShowNewOrderModal] = useState(false)

  const handleGoodsNumberChange = (value) => {
    setGoodsNumber(value)
    setTotalMoney(parseFloat((value * money).toFixed(2)))
  }

  const handleAddOrder = async () => {
    try {
      const params = {
        goodsId: Number(router.params.id),
        goodsNumber,
      }
      // console.log(params)
      const res = await addOrder(params)
      // if (res && res.data.orderId) {
      //   // console.log('orderId', res.data.orderId)
      //   Taro.atMessage({
      //     'message': '消息通知',
      //     'type': ''su,
      //   })
      //   Taro.navigateTo({
      //     url: `/pages/pay/index?id=${res.data.orderId}`,
      //   })
      // } else {
      //   console.error('无法获取订单ID')
      // }
      if (res.code == 0) {
        Taro.atMessage({
          message: '订单创建中...',
          type: 'success',
          duration: 1000,
        })
        // 等待消息通知结束后跳转
        setTimeout(() => {
          Taro.redirectTo({
            url: `/pages/pay/index?id=${res.data.orderId}`,
          })
        }, 1000) // 与消息通知的显示时长保持一致
      } else {
        Taro.atMessage({
          message: res.msg,
          type: 'warning',
          duration: 1000,
        })
      }
    } catch (error) {
      console.error('添加订单时发生错误:', error)
    }
  }

  const handleConfirm = () => {
    setShowNewOrderModal(false)
    handleAddOrder()
  }

  useLoad(() => {
    console.log('Page loaded.')
    console.log(router)

    const { id } = router.params
    console.log('准备商城订单的商品ID', id)

    const fetchGetGoodById = async () => {
      const res = await getGoodDetail(Number(id))
      console.log(res)
      setProductDetail(res.data.productDetail)
      setMoney(res.data?.productDetail.price)
      setTotalMoney(res.data?.productDetail.price)
    }
    fetchGetGoodById()
  })

  return (
    <>
      <div className={styles.pay}>
        <div className={styles.topPart}>
          <div className={styles.orderBox}>
            <div className={styles.orderDetail}>
              <img
                className={styles.goodPic}
                src={productDetail.coverUrl}
                alt=''
              />
              <div className={styles.goodInfo}>
                <div className={styles.goodDesc}>
                  {productDetail.description}
                </div>
                <div className={styles.goodPrice}>
                  <span>¥ {productDetail.price}</span>
                  <AtInputNumber
                    type='number'
                    min={1}
                    step={1}
                    value={goodsNumber}
                    onChange={handleGoodsNumberChange}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className={styles.footerPart}>
          <div className={styles.payMoney}>应付款金额：¥{totalMoney}</div>
          <div
            className={styles.payBtn}
            onClick={() => setShowNewOrderModal(true)}
          >
            立即支付
          </div>
        </div>
      </div>
      <AtModal
        isOpened={showModal}
        title='确认要离开收银台？'
        cancelText='取消'
        confirmText='确认'
        // onClose={handleModalCancel}
        onCancel={() => setShowModal(false)}
        // onConfirm={handleModalConfirm}
        content='您确定要离开收银台吗？'
      />
      <AtModal
        isOpened={showNewOrderModal}
        title='标题'
        cancelText='取消'
        confirmText='确认'
        onClose={() => setShowNewOrderModal(false)}
        onCancel={() => setShowNewOrderModal(false)}
        onConfirm={handleConfirm}
        content='此操作将会生成新的订单，是否继续？'
      />
      <AtMessage />
    </>
  )
}
